import React, { useEffect, useState } from 'react'
import {
  Card,
  Tree,
  Row,
  Col,
  Pagination,
  Tag,
  Table,
  Button,
  message,
} from 'antd'
import { useParams } from 'react-router-dom'

import {
  IdepList,
  IsrbookingRuleList,
  iScheduleListType,
} from '@/api/hospital/model/hospitalListTypes'
import {
  reqDepartments,
  reqScheduleRules,
  reqScheduleList,
} from '@api/hospital/hospitalList'

// 定义变量,存储当前页面用到的depcode
let depcode: string
export default function HospitalSchedule() {
  // 当前医院的hoscode
  const { hoscode } = useParams()
  // 定义存储所有科室数据的状态
  const [depList, setDepList] = useState<IdepList>([])
  // 存储了所有要展开的科室的depcode数组
  const [depcodeList, setDepCodeList] = useState<string[]>([])
  // 存储排班规则的数据
  const [scheduleRules, setScheduleRules] = useState<IsrbookingRuleList>([])
  // 存储排班列表的数据
  const [scheduleList, setScheduleList] = useState<iScheduleListType>([])

  // 选择部分动态渲染的三个
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')
  const [workDate, setWorkDate] = useState('')

  // 分页的三个状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(5)

  useEffect(() => {
    async function fetchData() {
      // 获取所有科室的数据
      // 这里给getDepList前面加await是希望所有科室数据获取成功之后,在执行后面获取排班规则的代码
      const result = await getDepList()
      // 获取排班规则, 默认传入的是 多发性硬化专科门诊的depcode
      depcode = result[0].children ? result[0].children[0].depcode : ''
      // 动态获取depname
      const depname = result[0].children ? result[0].children[0].depname : ''
      // 动态设置depname
      setDepname(depname)
      const bookingScheduleList = await getScheduleRules(
        page,
        pageSize,
        depcode
      )
      // 获取排班列表数据,默认获取scheduleRules里面第一条数据所对应的排班列表
      const workDate = bookingScheduleList[0].workDate
      setWorkDate(workDate)
      // 调用方法,获取排班列表数据
      getScheduleList(workDate)
    }
    fetchData()
  }, [])

  // 获取所有科室数据的方法
  async function getDepList() {
    const result = await reqDepartments(hoscode as string)
    // 让所有一级科室禁用,往对应的数据里面加disabled:true
    result.forEach((item) => {
      item.disabled = true
    })
    // 设置所有科室数据
    setDepList(result)
    // 拿到所有一级科室的depcode,然后存储起来.让所有一级科室展开
    setDepCodeList(result.map((item) => item.depcode))
    return result
  }
  // 获取排班规则的方法(Tag的数据)
  async function getScheduleRules(
    page: number,
    pageSize: number,
    depcode: string
  ) {
    const result = await reqScheduleRules({
      page,
      pageSize,
      hoscode: hoscode as string,
      depcode,
    })
    setScheduleRules(result.bookingScheduleList)
    setTotal(result.total)

    // 动态设置选择的医院名称
    setHosname(result.baseMap.hosname)

    return result.bookingScheduleList
  }
  // 获取当前排班列表数据的函数
  async function getScheduleList(workDate: string) {
    const result = await reqScheduleList(hoscode as string, depcode, workDate)
    setScheduleList(result)
  }
  // 选择科室时,触发的事件处理函数
  const onSelect = async (selectedKeys: any, info: any) => {
    console.log('selected', selectedKeys, info)
    // 修改渲染的科室名称
    try {
      setDepname(info.node.depname)
      // 重新获取指定科室的排班规则
      depcode = selectedKeys[0]
      const bookingScheduleList = await getScheduleRules(
        page,
        pageSize,
        depcode
      )
      // 动态设置选择的workDate
      const workDate = bookingScheduleList[0].workDate
      setWorkDate(workDate)

      getScheduleList(workDate)
    } catch (error) {
      message.error('暂无数据')
      setScheduleRules([])
      setScheduleList([])
      setWorkDate('')
    }
  }

  // 计算树形控件父元素的高度
  const treeWrapper = document.body.clientHeight - 64 - 34 - 24 * 2 - 14 - 22

  const columes = [
    {
      title: '序号',
      render: (text: any, record: any, index: number) => {
        return index + 1
      },
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'availableNumber',
    },
    {
      title: '剩余预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ]

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      <Row gutter={20}>
        <Col span={5}>
          <div
            style={{
              border: '1px solid #ccc',
              height: treeWrapper,
              overflow: 'auto',
            }}
          >
            <Tree
              defaultExpandedKeys={['0-0-0', '0-0-1']}
              onSelect={onSelect}
              treeData={depList as any}
              expandedKeys={depcodeList} // 让树结构的指定节点展开的配置项
              // Tree组件,默认展示的是treeData中的title和key.但是我们的数据中没有,对应的是depname和depcode,
              // 所以设置fieldName.告诉Tree组件去选渲染指定的数据
              fieldNames={{
                title: 'depname',
                key: 'depcode',
              }}
            />
          </div>
        </Col>
        <Col span={19}>
          {scheduleRules.map((item, index) => (
            // 动态渲染tag高亮
            <Tag
              color={workDate === item.workDate ? 'green' : ''}
              style={{
                cursor: 'pointer',
              }}
              key={index}
              onClick={() => {
                // 找到workDate
                setWorkDate(item.workDate)
                // 获取表格中的数据
                getScheduleList(item.workDate)
              }}
            >
              <div>
                {item.workDate} {item.dayOfWeek}
              </div>
              <div>
                {item.availableNumber} / {item.reservedNumber}
              </div>
            </Tag>
          ))}

          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            style={{ marginTop: 20, marginBottom: 20 }}
            showSizeChanger={true}
            onChange={async (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
              // 获取Tag数据
              const bookingScheduleList = await getScheduleRules(
                page,
                pageSize,
                depcode
              )
              // 修改workDate
              setWorkDate(bookingScheduleList[0].workDate)
              // 重新获取表格数据
              getScheduleList(bookingScheduleList[0].workDate)
            }}
          ></Pagination>
          <Table
            columns={columes}
            bordered
            dataSource={scheduleList}
            pagination={false}
            rowKey="id"
          ></Table>
          <Button style={{ marginTop: 20 }}>返回</Button>
        </Col>
      </Row>
    </Card>
  )
}
